from django.forms.models import model_to_dict
from rest_framework.views import APIView
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db import transaction

from todo_business.filters import IsOwnerFilterBackend
from .models import *
from rest_framework import routers, serializers, viewsets, filters, status
from .serializers import *
from django.utils.translation import ugettext as _
import json


class TodoTaskViewSet(viewsets.ModelViewSet):
    queryset = TodoTask.objects.all()
    serializer_class = TodoTaskSerializer
    filter_backends = [IsOwnerFilterBackend]

    def perform_create(self, serializer):
        todo_task = TodoTask()
        todo_task.task_name = self.request.data.get('task_name')


        serializer.save(author=self.request.user)

    @action(methods=['delete'], detail=False)
    def multiple(self, request):
        """
        批量删除任务 只能删除自己创建的任务
        """
        id_str = request.query_params.get('id')
        if id_str is None:
            return Response(status=status.HTTP_204_NO_CONTENT)
        ids = id_str.split(',')
        delete_result = self.queryset.filter(
            pk__in=ids).filter(author=request.user).delete()
        return Response(delete_result, status=status.HTTP_200_OK)


class TodoItemViewSet(viewsets.ModelViewSet):
    queryset = TodoItem.objects.all()
    serializer_class = TodoItemSerializer

    search_fields = ['todo_task']

    def get_queryset(self):
        items = TodoItem.objects.all()
        task_id = self.request.query_params.get('todo_task_id')
        if task_id is not None:
            items = items.filter(todo_task_id=task_id)
        return items

    @action(methods=['delete'], detail=False)
    def multiple(self, request):
        """
        批量删除待办项
        :param request:
        :return:
        """
        ids_str = request.query_params.get('id')

        if ids_str is None:
            return Response(status=status.HTTP_204_NO_CONTENT)

        ids = ids_str.split(',')
        self.queryset.filter(todo_task__author=request.user).filter(
            pk__in=ids).delete()

        return Response(status=status.HTTP_204_NO_CONTENT)


class TodoCategoryViewSet(viewsets.ModelViewSet):
    queryset = TodoCategory.objects.all()
    serializer_class = TodoCategorySerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


class TaskInCategoryViewSet(viewsets.ModelViewSet):
    queryset = TaskInCategory.objects.all()
    serializer_class = TaskInCategorySerializer


class ShareLinkViewSet(viewsets.ModelViewSet):
    queryset = ShareLink.objects.all()
    serializer_class = ShareLinkSerializer


class ShareLinkAPI(APIView):
    """分享待办"""
    @transaction.atomic
    def post(self, request):
        validated_data = request.data
        expires_after = validated_data["expires_after"]
        task_id = validated_data["task_id"]
        user = request.user

        task = TodoTask.objects.filter(id=task_id).first()
        if task is None:
            return Response({"success": False, "msg": "错误的待办，请检查是否存在！"})
        if task.author.id != user.id:
            return Response({"success": False, "msg": "待办不属于您，您无权分享！"})

        # 有效期根据设定计算出过期时间
        timedelta = datetime.timedelta(
            days=expires_after == 0 and 100000 or expires_after)
        expires_at = datetime.datetime.now() + timedelta

        # 判断分享是否存在
        instance = ShareLink.objects.filter(task__id=task_id).first()
        if instance is None:
            validated_data["expires_at"] = expires_at
            instance = ShareLink.objects.create(
                expires_after=expires_after, expires_at=expires_at, task=task)
        else:
            instance.expires_at = expires_at
            _dict = model_to_dict(instance)
            ShareLink.objects.update(**_dict)

        return Response({"success": True, "instance": model_to_dict(instance)})

    def get(self, request):
        params = request.query_params

        task_id = params.get("task_id")

        if task_id is None:
            return Response({"success": False})

        share_links = ShareLink.objects.filter(task__id=int(task_id))
        if len(share_links) == 0:
            return Response({"success": False, "msg": "待办不存在"})

        # 搞成数组
        data = []
        for item in share_links:
            data_item = model_to_dict(item)
            data_item["task"] = model_to_dict(item.task)
            data_item["is_expired"] = item.expires_at.replace(
                tzinfo=None) < datetime.datetime.now()
            data.append(data_item)

        return Response({"success": True, "data": data})

from django.db.models import Q

class ShareListAPI(APIView):
    """共享待办名单"""
    @transaction.atomic
    def post(self, request):
        user_id = request.user.id
        task_id = request.data["task_id"]

        # 尝试获取已存在的数据
        share_list = ShareList.objects.filter(
            task__id=task_id).filter(user__id=user_id).first()
        
        if share_list:
            share_list.cancelled= False
            share_list.save();
            share_list_dict= model_to_dict(share_list)
            # ShareLink.objects.save(share_list)
            return Response({"success": True, "data": share_list_dict})
        else:
            task= TodoTask.objects.filter(id= task_id).first()

            # 自己的待办不要写入共享列表
            if task.user.id == user_id:
                return Response({"success": True, "data": None})
            if task is None:
                return Response({"success": False, "msg": "代办已被删除，无法加入"})
            share_list= ShareList.objects.create(task= task, user= request.user)
            return Response({"success": True, "data": model_to_dict(share_list)})

    def get(self, request):
        user= request.user
        share_list= ShareList.objects.filter(Q(user_id= user.id) | Q(task__author= user) )

        data= []
        for item in share_list:
            data_item= model_to_dict(item)
            data_item["task"]= model_to_dict(item.task)
            data.append(data_item)

        return Response({"success": True, "data": data})
        
